<template>
  <div id="KnowledgeView">
    <Breadcrumb content="知识库预览" />
    <div class="bodyContent">
      <Splitpanes class="area">
        <Pane size="15">
          <el-scrollbar style="height: 100%">
            <el-tree ref="leftTree" :data="knowledgeCatalogAndContentTreeData" v-loading="showTreeLoading" :props="defaultProps" @node-click="handleNodeClick" class="tools-tree" node-key="id" default-expand-all highlight-current :current-node-key="currentTreeNode.id">
              <template #default="{ data }">
                <span
                  ><img :src="'../../../src/assets/images/Knowledge/' + data.knType + '.png'" style="width: 15px; height: 15px; margin-right: 10px" />
                  <div style="float: right">
                    {{ data.name }}
                  </div>
                </span>
              </template>
            </el-tree>
          </el-scrollbar>
        </Pane>
        <Pane size="85">
          <KnowledgeContent ref="knowledgeContentRef"></KnowledgeContent>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 =========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { Splitpanes, Pane } from 'splitpanes';
import KnowledgeContent from './KnowledgeContent.vue';
import NoData from '@/components/NoData.vue';

// 变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let showTreeLoading = ref(false);
let knowledgeCatalogAndContentTreeData = reactive([]);
const defaultProps = {
  children: 'children',
  label: 'name'
};
let currentTreeNode = reactive({
  id: '',
  code: '',
  pid: '',
  orgId: '',
  name: '',
  seq: 0,
  status: 0,
  knowledgeId: '',
  children: {}
});
//跳转前点击的当前树节点
let jumpCurrentTreeNode = reactive({
  id: '',
  code: '',
  pid: '',
  orgId: '',
  name: '',
  seq: 0,
  status: 0,
  knowledgeId: '',
  children: {}
});
let currentKnowledge = reactive({
  id: '',
  name: '',
  code: ''
});
const knowledgeContentRef: any = ref(null);

// ============ 方法定义区
onMounted(() => {
  currentKnowledge = proxy.$route.query;
  getKnowledgeCatalogAndContentTree();
});

// 获取目录与结果树
function getKnowledgeCatalogAndContentTree() {
  showTreeLoading.value = true;
  knowledgeCatalogAndContentTreeData.length = 0;
  const url = '/api/wk/wkKnowledgeCatalog/getKnowledgeCatalogAndContentTree/' + currentKnowledge.id;
  proxy.$http
    .get(url)
    .then((res: any) => {
      if (res.status.code !== 1) {
        proxy.$alert(res.status.msg, '提示');
      } else {
        knowledgeCatalogAndContentTreeData.push({
          id: currentKnowledge.id,
          name: currentKnowledge.name,
          code: currentKnowledge.code,
          knType: 'knowledge',
          level: 0,
          children: []
        });
        knowledgeCatalogAndContentTreeData[0].children.push(...res.data);
        if (knowledgeCatalogAndContentTreeData.length > 0) {
          currentTreeNode = findLeafNodes(knowledgeCatalogAndContentTreeData[0])[0];
          proxy.$nextTick(() => {
            jumpCurrentTreeNode = JSON.parse(localStorage.getItem('jumpCurrentTreeNodeStore'));
            if (jumpCurrentTreeNode) {
              proxy.$refs.leftTree.setCurrentKey(jumpCurrentTreeNode.id);
              handleNodeClick(jumpCurrentTreeNode);
              localStorage.removeItem('jumpCurrentTreeNodeStore'); //删除本地
            } else {
              proxy.$refs.leftTree.setCurrentKey(currentTreeNode.id);
              handleNodeClick(currentTreeNode);
            }
          });
        }
        showTreeLoading.value = false;
      }
    })
    .catch((err: any) => {
      VxeMessage('获取机构失败', VxeNotifyType.error);
      showTreeLoading.value = false;
    });
}

// 递归函数，用于查找树形结构中的叶子节点（即没有子节点的节点）
function findLeafNodes(node) {
  if (node.children.length === 0) {
    return [node];
  }
  return node.children.reduce((leafNodes, child) => {
    return leafNodes.concat(findLeafNodes(child));
  }, []);
}

// 点击树节点
function handleNodeClick(data: any) {
  jumpCurrentTreeNode = data;
  localStorage.setItem('jumpCurrentTreeNodeStore', JSON.stringify(jumpCurrentTreeNode));
  knowledgeContentRef.value?.initPage(currentKnowledge.id, data.id)
  knowledgeContentRef.value?.getContentListByCatalog(data.id);
}
</script>

<style lang="scss" scoped>
#KnowledgeView {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .area {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .el-tree {
        padding-top: 5px;
        height: calc(100% - 5px);
      }
    }
  }
}
</style>
